﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Masterduner.SourceStudio.Practices.DevelopmentLibrary.Data.SqlClient;
using Masterduner.SourceStudio.Practices.DevelopmentLibrary.Utilities.DataConfiguration.Windows;

namespace Masterduner.SourceStudio.Practices.DevelopmentLibrary.Utilities.DataConfiguration.Controls
{
    public partial class ConfigurationLoader : UserControl
    {
        private FileInfo _configurationFile;
        private int _protectionProvider;

        public ConfigurationLoader()
        {
            InitializeComponent();
            this.SetProtectionNameBackgroundColor();
            this.SetSplitContainerPanelsBackgroundColor();
            this.SetFeatureTreeBackgroundColor();
            this.InitializeFeatureTree();
        }

        #region ConfigurationFile
        public FileInfo ConfigurationFile
        {
            get { return _configurationFile; }
            set { _configurationFile = value; }
        }
        #endregion

        #region SetProtectionNameBackgroundColor
        private void SetProtectionNameBackgroundColor()
        {
            this.panProtections.BackColor = ColorTranslator.FromHtml("#16160E");
        }
        #endregion

        #region SetFeatureTreeBackgroundColor
        private void SetFeatureTreeBackgroundColor()
        {
            this.tvFeautures.BackColor = this.splitContainer1.Panel1.BackColor;
        }
        #endregion

        #region SetSplitContainerPanelsBackgroundColor
        private void SetSplitContainerPanelsBackgroundColor()
        {
            this.splitContainer1.Panel1.BackColor = ColorTranslator.FromHtml("#00A497");
            this.splitContainer1.Panel2.BackColor = ColorTranslator.FromHtml("#93CA76");
        }
        #endregion

        #region ProtectionProvider
        public int ProtectionProvider
        {
            get { return _protectionProvider; }
            private set { _protectionProvider = value; }
        }
        #endregion

        #region pbDropButton_Click
        private void pbDropButton_Click(object sender, System.EventArgs e)
        {
            Point p = this.PointToScreen(this.panControls1.Location);
            using (ProtectionOptionsWindow optionsWindow = new ProtectionOptionsWindow()
            {
                Location = new Point(p.X + 5, p.Y + 43)
            })
            {
                if (optionsWindow.ShowDialog() == DialogResult.OK)
                {
                    this.ProtectionProvider = optionsWindow.ProtectionProvider;
                    this.labProtection.Text = string.Format("({0})", optionsWindow.SelectedText);
                }
            }
        }
        #endregion

        #region CreateChildFeatureNodeFontStyle
        private Font CreateChildFeatureNodeFontStyle()
        {
            return new Font("微软雅黑", 10, FontStyle.Italic);
        }
        #endregion

        #region CreateDefaultDataProviderNode
        private TreeNode CreateDefaultDataProviderNode()
        {
            return this.CreateDataProviderNode("System.Data.SqlClient", typeof(SqlDatabase).AssemblyQualifiedName, true);
        }
        #endregion

        #region CreateDataProviderNode
        private TreeNode CreateDataProviderNode(string name, string type, bool isDefault = false)
        {
            return new TreeNode(name)
            {
                ForeColor = Color.White,
                NodeFont = this.CreateChildFeatureNodeFontStyle(),
                Tag = new
                {
                    Name = name,
                    Type = type,
                    Mode = 1,
                    IsDefault = isDefault
                },
                ContextMenuStrip = this.contextMenuStrip2
            };
        }
        #endregion

        #region InitializeFeatureTree
        private void InitializeFeatureTree()
        {
            this.tvFeautures.Nodes[0].Nodes.Add(this.CreateDefaultDataProviderNode());
            this.tvFeautures.ExpandAll();
        }
        #endregion

        #region miCreateDatabase_Click
        private void miCreateDatabase_Click(object sender, System.EventArgs e)
        {
            using (DatabaseAssemblyLoadWindow assLoadWindow = new DatabaseAssemblyLoadWindow())
            {
                if (assLoadWindow.ShowDialog() == DialogResult.OK)
                {
                    if (!assLoadWindow.DatabaseName.IsEmptyOrWriteSpaces() && !assLoadWindow.DatabaseType.IsEmptyOrWriteSpaces())
                    {
                        this.tvFeautures.Nodes[0].Nodes.Add(this.CreateDataProviderNode(assLoadWindow.DatabaseName, assLoadWindow.DatabaseType));
                    }
                }
            }
        }
        #endregion

        #region tvFeautures_NodeMouseClick
        private void tvFeautures_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (e.Node.Level.Equals(0)) this.splitContainer1.Panel2.Controls.Clear();
                else
                {
                    this.splitContainer1.Panel2.Controls.Clear();
                    this.splitContainer1.Panel2.Controls.Add(this.WhichControlRequiredLoad(e.Node.Tag));
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                this.tvFeautures.SelectedNode = e.Node;
            }
        }
        #endregion

        #region WhichControlRequiredLoad
        private UserControl WhichControlRequiredLoad(dynamic arg)
        {
            if (arg.Mode == 1) return new DatabaseProviderDescription() { DatabaseName = arg.Name, DatabaseType = arg.Type, Dock = DockStyle.Fill };
            else return new ConnectionDescription()
            {
                ConnectionName = arg.Name,
                ConnectionString = arg.ConnectionString,
                ErrorHandleMode = ((Data.DatabaseExceptionProcessMode)arg.ErrorHandleMode).ToString(),
                ProviderName = arg.Provider,
                CommandTimeout = arg.Timeout
            };
        }
        #endregion

        #region deleteDataProvider_Click
        private void deleteDataProvider_Click(object sender, EventArgs e)
        {
            dynamic tagObject = this.tvFeautures.SelectedNode.Tag;
            if (tagObject.IsDefault)
            {
                throw new Exception("此数据库是默认的，不可以删除！");
            }
            this.tvFeautures.SelectedNode.Remove();
        }
        #endregion

        #region miCreateDbConnectionString_Click
        private void miCreateDbConnectionString_Click(object sender, EventArgs e)
        {
            List<string> providers = new List<string>();
            foreach (TreeNode item in this.tvFeautures.Nodes[0].Nodes) providers.Add(item.Text);
            using (ConnectionStringBuilderWindow wsbWindow = new ConnectionStringBuilderWindow() { DatabaseProviders = providers.ToArray() })
            {
                if (wsbWindow.ShowDialog() == DialogResult.OK)
                {
                    if (!wsbWindow.ConnectionString.IsEmptyOrWriteSpaces() && !wsbWindow.ProviderName.IsEmptyOrWriteSpaces() && !wsbWindow.ConnectionName.IsEmptyOrWriteSpaces())
                    {
                        this.tvFeautures.Nodes[1].Nodes.Add(new TreeNode(wsbWindow.ConnectionName)
                        {
                            NodeFont = this.CreateChildFeatureNodeFontStyle(),
                            ForeColor = Color.White,
                            Tag = new
                            {
                                Name = wsbWindow.ConnectionName,
                                Provider = wsbWindow.ProviderName,
                                Timeout = wsbWindow.ExecuteTimeout,
                                ErrorHandleMode = wsbWindow.ExceptionHandlingMode,
                                ConnectionString = wsbWindow.ConnectionString,
                                Mode = 2
                            },
                            ContextMenuStrip = this.contextMenuStrip4
                        });
                        this.tvFeautures.ExpandAll();
                    }
                }
            }
        }
        #endregion

        #region miRemoveConnection_Click
        private void miRemoveConnection_Click(object sender, EventArgs e)
        {
            this.tvFeautures.SelectedNode.Remove();
        }
        #endregion

        #region RequiredSaveToUserConfig
        public bool RequiredSaveToUserConfig()
        {
            return this.cbWriteToUserConfig.Checked;
        }
        #endregion

        #region ShowSaveDialog
        public DialogResult ShowSaveDialog(out string fileName)
        {
            DialogResult result = this.saveFileDialog1.ShowDialog();
            fileName = this.saveFileDialog1.FileName;
            return result;
        }
        #endregion

        #region GetDatabases
        public List<dynamic> GetDatabases()
        {
            List<dynamic> list = new List<dynamic>();
            foreach (TreeNode item in this.tvFeautures.Nodes[0].Nodes)
                list.Add(item.Tag);
            return list;
        }
        #endregion

        #region GetConnections
        public List<dynamic> GetConnections()
        {
            List<dynamic> list = new List<dynamic>();
            foreach (TreeNode item in this.tvFeautures.Nodes[1].Nodes)
                list.Add(item.Tag);
            return list;
        }
        #endregion
    }
}
